import {fileChoiceType} from '@/utils/file-choice/config'
import toast from '@/utils/toast'

//选择file类
class FileChoice {
  //私有属性
  #fileChoice

  constructor(fileType) {
    this.#fileChoice = fileChoiceType[fileType]
  }

  //选择
  choose(count = 1) {
    return new Promise((resolve, reject) => {
      //选择文件
      this.#fileChoice({
        count: count,
        sourceType: ['album'],
        success(res) {
          const tempFiles = res.tempFiles || [res.tempFile]
          const tempFilePaths = res.tempFilePaths || [res.tempFilePath]

          //判断选择的长度
          if (count === 1) {
            const filename = tempFiles[0].name
            const path = tempFilePaths[0]
            resolve({filename, path})
            return
          }

          //如果多个文件则返回数组
          const fileArray = []
          for (let i = 0; i < tempFilePaths.length; i++) {
            const filename = tempFiles[i].name
            const path = tempFilePaths[i]
            fileArray.push({filename, path})
          }
          resolve(fileArray)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  //上传
  upload({path, filename}, folder, mediaType = 'images') {
    //显示加载框
    toast.loading('上传中 0...')
    return new Promise((resolve, reject) => {
      uniCloud.uploadFile({
        filePath: path,
        cloudPath: `${mediaType}/${folder}/${Date.now()}_${filename}`,
        onUploadProgress({loaded, total}) {
          const percent = Math.round((loaded * 100) / total) - 1
          toast.loading(`上传中 ${percent}...`)
        },
        success({fileID}) {
          //隐藏加载框
          toast.hideLoading()
          resolve(fileID)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  //请求URL地址
  requestUrl(fileID) {
    return new Promise((resolve, reject) => {
      uniCloud.getTempFileURL({
        fileList: [fileID],
        success: res => {
          resolve(res.fileList[0].tempFileURL)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }
}

//创建图片选择实例
export const imageFileChoice = new FileChoice('image')
export const videoFileChoice = new FileChoice('video')
